<template>
  <div class="stock-page">
    <!-- 库存概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon total">
              <el-icon size="24"><Box /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ stockOverview.totalProducts }}</div>
              <div class="card-label">商品总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon warning">
              <el-icon size="24"><Warning /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ stockOverview.lowStockProducts }}</div>
              <div class="card-label">库存预警</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon danger">
              <el-icon size="24"><CircleClose /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ stockOverview.outOfStockProducts }}</div>
              <div class="card-label">缺货商品</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon success">
              <el-icon size="24"><Check /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ stockOverview.normalStockProducts }}</div>
              <div class="card-label">库存正常</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 库存管理主区域 -->
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>库存管理</h3>
          <div class="header-actions">
            <el-button type="warning" @click="handleBatchReplenish" :disabled="selectedRows.length === 0">
              <el-icon><Plus /></el-icon>
              批量补货
            </el-button>
            <el-button type="primary" @click="showAutoReplenishDialog">
              <el-icon><Setting /></el-icon>
              自动补货设置
            </el-button>
            <el-button type="success" @click="handleStockAdjustment">
              <el-icon><Edit /></el-icon>
              库存调整
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
          </el-form-item>
          <el-form-item label="商品编码">
            <el-input v-model="searchForm.code" placeholder="请输入商品编码" clearable />
          </el-form-item>
          <el-form-item label="仓库">
            <el-select v-model="searchForm.warehouse" placeholder="请选择仓库" clearable>
              <el-option label="主仓库" value="主仓库" />
              <el-option label="分仓库A" value="分仓库A" />
              <el-option label="分仓库B" value="分仓库B" />
            </el-select>
          </el-form-item>
          <el-form-item label="库存状态">
            <el-select v-model="searchForm.stockStatus" placeholder="请选择库存状态" clearable>
              <el-option label="正常" value="正常" />
              <el-option label="预警" value="预警" />
              <el-option label="缺货" value="缺货" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table 
        :data="tableData" 
        v-loading="loading" 
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="商品编码" width="120" />
        <el-table-column prop="name" label="商品名称" width="200" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="warehouse" label="仓库" width="100" />
        <el-table-column prop="currentStock" label="当前库存" width="100">
          <template #default="{ row }">
            <el-tag :type="getStockStatusType(row.currentStock, row.minStock)">
              {{ row.currentStock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="minStock" label="最低库存" width="100" />
        <el-table-column prop="maxStock" label="最高库存" width="100" />
        <el-table-column prop="safetyStock" label="安全库存" width="100" />
        <el-table-column prop="stockStatus" label="库存状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStockStatusTagType(row.stockStatus)">
              {{ row.stockStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastInDate" label="最后入库" width="120" />
        <el-table-column prop="lastOutDate" label="最后出库" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleReplenish(row)">
              补货
            </el-button>
            <el-button type="info" size="small" @click="handleAdjust(row)">
              调整
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 库存详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="库存详情"
      width="800px"
    >
      <div v-if="currentStock">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品编码">{{ currentStock.code }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ currentStock.name }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ currentStock.category }}</el-descriptions-item>
          <el-descriptions-item label="仓库">{{ currentStock.warehouse }}</el-descriptions-item>
          <el-descriptions-item label="当前库存">{{ currentStock.currentStock }}</el-descriptions-item>
          <el-descriptions-item label="最低库存">{{ currentStock.minStock }}</el-descriptions-item>
          <el-descriptions-item label="最高库存">{{ currentStock.maxStock }}</el-descriptions-item>
          <el-descriptions-item label="安全库存">{{ currentStock.safetyStock }}</el-descriptions-item>
          <el-descriptions-item label="库存状态">
            <el-tag :type="getStockStatusTagType(currentStock.stockStatus)">
              {{ currentStock.stockStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后入库">{{ currentStock.lastInDate }}</el-descriptions-item>
          <el-descriptions-item label="最后出库">{{ currentStock.lastOutDate }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentStock.remark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider>库存变动记录</el-divider>
        <el-table :data="stockHistory" border>
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="row.type === '入库' ? 'success' : 'danger'">
                {{ row.type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="beforeStock" label="变动前" width="100" />
          <el-table-column prop="afterStock" label="变动后" width="100" />
          <el-table-column prop="operator" label="操作人" width="100" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 补货对话框 -->
    <el-dialog
      v-model="replenishDialogVisible"
      title="库存补货"
      width="500px"
    >
      <el-form
        ref="replenishFormRef"
        :model="replenishForm"
        :rules="replenishRules"
        label-width="100px"
      >
        <el-form-item label="商品名称">
          <el-input :value="currentStock?.name" disabled />
        </el-form-item>
        
        <el-form-item label="当前库存">
          <el-input :value="currentStock?.currentStock" disabled />
        </el-form-item>

        <el-form-item label="补货数量" prop="quantity">
          <el-input-number 
            v-model="replenishForm.quantity" 
            :min="1"
            style="width: 100%"
            placeholder="请输入补货数量"
          />
        </el-form-item>

        <el-form-item label="供应商" prop="supplier">
          <el-select v-model="replenishForm.supplier" placeholder="请选择供应商" style="width: 100%">
            <el-option label="苹果供应商" value="苹果供应商" />
            <el-option label="华为供应商" value="华为供应商" />
            <el-option label="小米供应商" value="小米供应商" />
          </el-select>
        </el-form-item>

        <el-form-item label="预计到货" prop="expectedDate">
          <el-date-picker
            v-model="replenishForm.expectedDate"
            type="date"
            placeholder="请选择预计到货日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="replenishForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注" 
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="replenishDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleReplenishSubmit" :loading="replenishLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 自动补货设置对话框 -->
    <el-dialog
      v-model="autoReplenishDialogVisible"
      title="自动补货设置"
      width="600px"
    >
      <el-form
        ref="autoReplenishFormRef"
        :model="autoReplenishForm"
        :rules="autoReplenishRules"
        label-width="120px"
      >
        <el-form-item label="启用自动补货" prop="enabled">
          <el-switch 
            v-model="autoReplenishForm.enabled" 
            active-text="启用" 
            inactive-text="禁用"
          />
        </el-form-item>

        <el-form-item label="补货触发条件" prop="triggerCondition">
          <el-radio-group v-model="autoReplenishForm.triggerCondition">
            <el-radio label="低于最低库存">低于最低库存</el-radio>
            <el-radio label="低于安全库存">低于安全库存</el-radio>
            <el-radio label="库存为0">库存为0</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="补货数量规则" prop="replenishRule">
          <el-radio-group v-model="autoReplenishForm.replenishRule">
            <el-radio label="补到最高库存">补到最高库存</el-radio>
            <el-radio label="补到安全库存">补到安全库存</el-radio>
            <el-radio label="固定数量">固定数量</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item 
          v-if="autoReplenishForm.replenishRule === '固定数量'" 
          label="固定数量" 
          prop="fixedQuantity"
        >
          <el-input-number 
            v-model="autoReplenishForm.fixedQuantity" 
            :min="1"
            style="width: 200px"
            placeholder="请输入固定数量"
          />
        </el-form-item>

        <el-form-item label="默认供应商" prop="defaultSupplier">
          <el-select v-model="autoReplenishForm.defaultSupplier" placeholder="请选择默认供应商" style="width: 100%">
            <el-option label="苹果供应商" value="苹果供应商" />
            <el-option label="华为供应商" value="华为供应商" />
            <el-option label="小米供应商" value="小米供应商" />
          </el-select>
        </el-form-item>

        <el-form-item label="自动创建采购单" prop="autoCreatePO">
          <el-switch 
            v-model="autoReplenishForm.autoCreatePO" 
            active-text="是" 
            inactive-text="否"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="autoReplenishDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAutoReplenishSubmit" :loading="autoReplenishLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const viewDialogVisible = ref(false)
const replenishDialogVisible = ref(false)
const autoReplenishDialogVisible = ref(false)
const replenishLoading = ref(false)
const autoReplenishLoading = ref(false)
const replenishFormRef = ref()
const autoReplenishFormRef = ref()
const selectedRows = ref([])
const currentStock = ref(null)

// 库存概览数据
const stockOverview = reactive({
  totalProducts: 156,
  lowStockProducts: 12,
  outOfStockProducts: 3,
  normalStockProducts: 141
})

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  warehouse: '',
  stockStatus: ''
})

// 补货表单
const replenishForm = reactive({
  quantity: 1,
  supplier: '',
  expectedDate: '',
  remark: ''
})

// 自动补货设置表单
const autoReplenishForm = reactive({
  enabled: true,
  triggerCondition: '低于最低库存',
  replenishRule: '补到最高库存',
  fixedQuantity: 1,
  defaultSupplier: '',
  autoCreatePO: true
})

// 表单验证规则
const replenishRules = {
  quantity: [
    { required: true, message: '请输入补货数量', trigger: 'blur' }
  ],
  supplier: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  expectedDate: [
    { required: true, message: '请选择预计到货日期', trigger: 'change' }
  ]
}

const autoReplenishRules = {
  defaultSupplier: [
    { required: true, message: '请选择默认供应商', trigger: 'change' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    code: 'P001',
    name: 'iPhone 15',
    category: '电子产品',
    warehouse: '主仓库',
    currentStock: 5,
    minStock: 10,
    maxStock: 100,
    safetyStock: 20,
    stockStatus: '预警',
    lastInDate: '2024-01-10',
    lastOutDate: '2024-01-15',
    remark: '热销商品'
  },
  {
    id: 2,
    code: 'P002',
    name: 'MacBook Pro',
    category: '电子产品',
    warehouse: '主仓库',
    currentStock: 0,
    minStock: 5,
    maxStock: 50,
    safetyStock: 10,
    stockStatus: '缺货',
    lastInDate: '2024-01-08',
    lastOutDate: '2024-01-14',
    remark: '高端产品'
  },
  {
    id: 3,
    code: 'P003',
    name: 'Nike运动鞋',
    category: '服装鞋帽',
    warehouse: '分仓库A',
    currentStock: 156,
    minStock: 50,
    maxStock: 500,
    safetyStock: 100,
    stockStatus: '正常',
    lastInDate: '2024-01-12',
    lastOutDate: '2024-01-13',
    remark: '库存充足'
  }
])

// 库存变动记录
const stockHistory = ref([
  {
    date: '2024-01-15',
    type: '出库',
    quantity: 3,
    beforeStock: 8,
    afterStock: 5,
    operator: '张三',
    remark: '销售出库'
  },
  {
    date: '2024-01-10',
    type: '入库',
    quantity: 20,
    beforeStock: 0,
    afterStock: 20,
    operator: '李四',
    remark: '采购入库'
  }
])

// 计算属性
const getStockStatusType = (currentStock, minStock) => {
  if (currentStock === 0) return 'danger'
  if (currentStock <= minStock) return 'warning'
  return 'success'
}

const getStockStatusTagType = (status) => {
  const statusMap = {
    '正常': 'success',
    '预警': 'warning',
    '缺货': 'danger'
  }
  return statusMap[status] || 'info'
}

// 方法
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    warehouse: '',
    stockStatus: ''
  })
  handleSearch()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleView = (row) => {
  currentStock.value = row
  viewDialogVisible.value = true
}

const handleReplenish = (row) => {
  currentStock.value = row
  replenishDialogVisible.value = true
  resetReplenishForm()
}

const handleAdjust = (row) => {
  ElMessage.info('跳转到库存调整页面')
}

const handleBatchReplenish = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要补货的商品')
    return
  }
  ElMessage.info(`批量补货 ${selectedRows.value.length} 个商品`)
}

const handleStockAdjustment = () => {
  ElMessage.info('跳转到库存调整页面')
}

const showAutoReplenishDialog = () => {
  autoReplenishDialogVisible.value = true
}

const handleReplenishSubmit = async () => {
  if (!replenishFormRef.value) return

  try {
    await replenishFormRef.value.validate()
    replenishLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 更新库存
    const index = tableData.value.findIndex(item => item.id === currentStock.value.id)
    if (index > -1) {
      tableData.value[index].currentStock += replenishForm.quantity
      tableData.value[index].stockStatus = getStockStatus(tableData.value[index].currentStock, tableData.value[index].minStock)
    }

    ElMessage.success('补货申请提交成功')
    replenishDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    replenishLoading.value = false
  }
}

const handleAutoReplenishSubmit = async () => {
  if (!autoReplenishFormRef.value) return

  try {
    await autoReplenishFormRef.value.validate()
    autoReplenishLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success('自动补货设置保存成功')
    autoReplenishDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    autoReplenishLoading.value = false
  }
}

const resetReplenishForm = () => {
  Object.assign(replenishForm, {
    quantity: 1,
    supplier: '',
    expectedDate: '',
    remark: ''
  })
  replenishFormRef.value?.clearValidate()
}

const getStockStatus = (currentStock, minStock) => {
  if (currentStock === 0) return '缺货'
  if (currentStock <= minStock) return '预警'
  return '正常'
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.stock-page {
  padding: 0;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
}

.card-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.warning {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.danger {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
}

.card-icon.success {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
